<template>
  <div>
    <el-form :model="params" ref="ruleForm" label-position="right" size="small" label-width="110px" class="base-search-more">
      <el-row>
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="区域">
            <agent-list style="width: 100%" :agentids="params.agentId" v-on:listenToChildEvent="getAentId" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="日期">
            <pt-date-picker v-model="params.date" :shortcuts="[{ text: '今天', start: 0, end: 0},{ text: '近七天', start: -7, end: 0}, {text: '近一个月', start: -30, end: 0}]" />
          </el-form-item>
        </el-col>
        <el-col :span="$store.state.showAgent? 12: 18" style="text-align: right;">
          <el-form-item label-width="0">
            <el-button @click="exportExcel()" v-loading="ExcelLoading">导出表格<i class="el-icon-download"></i></el-button>
            <el-button type="primary" icon="el-icon-search" @click="$refs.pagination.handleSizeChange(10)">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="base-table-wrap">
      <el-table :data="serialization(tableData.list)">
        <el-table-column prop="agentname" label="区域名称" min-width="140" align="left" />
        <el-table-column prop="transactionAmount" min-width="120" align="right">
         <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="用户实际支付的金额" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>有效交易额
          </template>
        </el-table-column>
        <el-table-column prop="count1" min-width="120" align="right">
         <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="已完成的有效订单，支付后取消或其他全额退款的订单除外" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>有效订单量
          </template>
        </el-table-column>
        <el-table-column prop="goodsTotalSum" min-width="100" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="有效订单内的商品数量" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商品销量
          </template>
        </el-table-column>
        <el-table-column prop="actualRakeTurnover" min-width="120" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="(商品实付价格+包装费)/实抽佣营业额" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商品销量额
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" min-width="145" align="right">
         <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="(商品原价+包装费)/原抽佣营业额" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商品折前销售额
          </template>
        </el-table-column>
        <el-table-column prop="merchantDeliveryRevenue" min-width="130" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="自配送费收益，不参与抽佣计算" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商家配送盈收
          </template>
        </el-table-column>
        <el-table-column prop="merchantSubsidyAmount" min-width="130" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="区域满减活动补贴商家承担部分+区域配送费活动补贴商家承担部分+首单立减活动补贴商家承担部分+商家特价支出+客户使用了的优惠券支出" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商家活动支出
          </template>
        </el-table-column>
        <el-table-column prop="serviceFee" min-width="90" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="即实抽佣盈收，区分折前折后" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>服务费
          </template>
        </el-table-column>
        <el-table-column prop="merchantRevenue" min-width="100" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="商家折前销售额+商家自配送盈收-商家活动支出-服务费" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商家收入
          </template>
        </el-table-column>
        <el-table-column prop="originalDistributionIncome" min-width="145" align="right">
           <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="有效订单内所有的配送费之和，不计入配送类优惠" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>区域原配送盈收
          </template>
        </el-table-column>
        <el-table-column prop="realDistributionSurplus" min-width="145" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="用户支付的配送费，即有效订单内所有实际收取的配送费之和" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>区域实配送盈收
          </template>
        </el-table-column>
        <el-table-column prop="platformSubsidyAmount" min-width="130" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="区域满减活动补贴代理商承担部分+区域配送费活动补贴代理商承担部分+首单立减活动补贴代理商承担部分+客户使用了的代理商红包" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>区域活动支出
          </template>
        </el-table-column>
        <el-table-column prop="riderTakeawayCommission" min-width="130" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="1.配送费距离小于基础配送距离，基本配送提成+特殊时段提成。2.超出基础距离，基础配送提出+超出距离部分提成+特殊时段提成。3.如果1和2计算结果大于每单最高提成，则按照每单最高提成计算" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>骑手外卖佣金
          </template>
        </el-table-column>
        <el-table-column prop="regionalNetProfit" min-width="120" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="服务费+区域原配送盈收-区域活动补贴-骑手外卖佣金" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>区域净利润
          </template>
        </el-table-column>
      </el-table>
      <pt-table-loading v-show="isloadingTable" />
      <pt-pagination ref="pagination" :total="tableData.count" @listeningEvent="triggerEvent" />
    </div>
    <el-table v-show="false" :data="ExTableData" :summary-method="getSummaries" show-summary id="out-table" >  <!--不显示的表格下载-->
      <el-table-column prop="agentname" label="区域名称" />
      <el-table-column prop="transactionAmount" label="交易额" />
      <el-table-column prop="count1" label="有效订单量" />
      <el-table-column prop="goodsTotalSum" label="商品销量" />
      <el-table-column prop="actualRakeTurnover" label="商品销量额" />
      <el-table-column prop="originalPrice" label="商品折前销售额" />
      <el-table-column prop="merchantDeliveryRevenue" label="商品配送盈收" />
      <el-table-column prop="merchantSubsidyAmount" label="商家活动支出" />
      <el-table-column prop="serviceFee" label="服务费" />
      <el-table-column prop="merchantRevenue" label="商家收入" />
      <el-table-column prop="originalDistributionIncome" label="区域原配送盈收" />
      <el-table-column prop="realDistributionSurplus" label="区域实配送盈收" />
      <el-table-column prop="platformSubsidyAmount" label="区域活动支出" />
      <el-table-column prop="riderTakeawayCommission" label="骑手外卖佣金" />
      <el-table-column prop="regionalNetProfit" label="区域净利润" />
    </el-table>
  </div>
</template>
<script>
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
  import acction from '@/utils/acction.js'
  import { getDay } from '@/utils/ptkc.js'
  export default {
    data() {
      return {
        params: { //查询数据
          page: 0,
          size: 10,
          date: [getDay(-30) + ' ' + '00:00:00', getDay(0) + ' ' + '23:59:59'],
          isdelive: 1,
          agentId: []
        },
        isloadingTable: false,
        ExcelLoading: false,
        ExTableData: [], //表格数据
        tableData: {}, //表单数据
        total: null
      }
    },
    methods: {
      getAentId(item) { //获取子组件传递的区域
        this.params.agentId = item
      },
      triggerEvent(type,val) { // 分页器
        if (type === 'page') {
          this.params.page = val - 1
        } else if (type === 'size') {
          this.params.page = 0
          this.params.size = val
        }
        this.getTableList()
      },
      serialization(arr) { // 序列化数组null转0
        const newArr = []
        if (arr &&arr.length) {
          for (let i = 0; i< arr.length; i++) {
            const obj = {}
            for (const key in arr[i]) {
              if (key === 'agentname') {
                obj[key] = arr[i][key] || ''
              } else if (key === 'count1' || key === 'goodsTotalSum') {
                obj[key] = arr[i][key] || 0
              } else {
                obj[key] = arr[i][key] ? arr[i][key].toFixed(2) : '0.00'
              }
            }
            newArr.push(obj)
          }
        }
        return newArr
      },
      getSummaries(param) { // 表格统计
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return new acction(prev,curr).accAdd()
              } else {
                return prev
              }
            }, 0)
            //sums[index] += ' 元';
          } else {
            sums[index] = 'N/A'
          }
        })
        return sums
      },
      exportExcel() { // 导出表格
        this.ExcelLoading = true
        const params = { ...this.params }
        params.createtime1 = params.date?params.date[0] : ''
        params.createtime2 = params.date?params.date[1] : ''
        params.agentId = params.agentId.length > 0 ? params.agentId.join(',') : ''
        params.page = 0
        params.size = this.total
        delete params.date
        this.$http.get('/server/business/agentnamemoney?'+ this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.ExTableData = this.serialization(res.data.list)
            setTimeout(() => {
              this.ExcelLoading = false
              var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
              var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'})
              try {
                FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), `${params.createtime1.slice(0,10)}-${params.createtime2.slice(0,10)}.xls`)
              } catch (e) {
                if (typeof console !== 'undefined') this.ExcelLoading = false
              }
              return wbout
            }, 500)
          }
        }).finally(() => { this.ExcelLoading = false })
      },
      getTableList() { //获取订单数据
        const params = { ...this.params }
        params.createtime1 = params.date?params.date[0] : ''
        params.createtime2 = params.date?params.date[1] : ''
        params.agentId = params.agentId.length > 0 ? params.agentId.join(',') : ''
        delete params.date
        this.isloadingTable = true
        this.$http.get('/server/business/agentnamemoney?'+ this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.total = res.data.count
            this.tableData = res.data
          }
        }).finally(() => { this.isloadingTable = false })
      }
    },
    mounted() {
      this.getTableList()
    }
  }
</script>

<style scoped>
  .header {
    padding: 15px 15px 0 15px;
    background: #fff;
    border-bottom: 1px solid #e5e5e5;
  }
</style>
